package tree;

import java.util.Arrays;

/**
 * 堆排序
 */
public class heap {
    public static void main(String[] args) {
        int[] arr = {11, 35, 5, 34, 87, 55, 88, 37};
        System.out.println(Arrays.toString(arr));
        heapSort(arr);
    }

    /**
     * 堆排序
     *
     * @param arr
     */
    public static void heapSort(int[] arr) {
        System.out.println("开始堆排序");
        for (int i = arr.length / 2 - 1; i >= 0; i--) {
            adjust(arr, i, arr.length);
        }
        //堆顶元素放到数组最后，然后再调整堆
        for (int i = arr.length - 1; i > 0; i--) {
            int temp = arr[i];
            arr[i] = arr[0];
            arr[0] = temp;
            adjust(arr, 0, i);
        }

        System.out.println(Arrays.toString(arr));
    }

    /**
     * 调整堆
     *
     * @param arr
     * @param i
     * @param length
     */
    public static void adjust(int[] arr, int i, int length) {
        int temp = arr[i];
        for (int k = i * 2 + 1; k < length; k = k * 2 + 1) {
            if ((k + 1) < length && arr[k] < arr[k + 1]) {
                k++;
            }
            if (arr[k] > temp) {
                arr[i] = arr[k];
                i = k;
            } else {
                break;
            }
        }
        arr[i] = temp;
    }
}
